package com.innext.kjqb.ui.authentication_new.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.innext.kjqb.R;
import com.innext.kjqb.app.App;
import com.innext.kjqb.base.BaseFragment;
import com.innext.kjqb.config.Constant;
import com.innext.kjqb.events.AuthenticationCenterEvent;
import com.innext.kjqb.util.SpUtil;
import com.innext.kjqb.util.ViewUtil;
import com.innext.kjqb.widget.loading.LoadingLayout;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;

/**
 * Created by gyl on 2017/6/13 0013.
 * 运营商
 */

public class OperatorFragment extends BaseFragment {
    @BindView(R.id.web_view)
    WebView mWebView;
    @BindView(R.id.tv_tag_content)
    TextView mTvTagContent;
    @BindView(R.id.dialog_view)
    LinearLayout mDialogView;
    @BindView(R.id.loading_layout)
    LoadingLayout mLoadingLayout;

    private String mPhoneInfoUrl;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_operator;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void loadData() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            mPhoneInfoUrl = bundle.getString("PhoneInfoUrl");
        }
        initView();
        if (!TextUtils.isEmpty(mPhoneInfoUrl)) {
            mPhoneInfoUrl = getUrl(mPhoneInfoUrl);
            mWebView.loadUrl(mPhoneInfoUrl);

        }
    }

    private void initView() {
        mWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setAllowFileAccess(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setDomStorageEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setDatabaseEnabled(true);
        //webview在安卓5.0之前默认允许其加载混合网络协议内容
        // 在安卓5.0之后，默认不允许加载http与https混合内容，需要设置webview允许其加载混合网络协议内容
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.addJavascriptInterface(new JavaMethod(), "nativeMethod");
    }

    public class JavaMethod {
        /**
         * 运营商认证完成
         */
        @JavascriptInterface
        public void complete() {
            EventBus.getDefault().post(new AuthenticationCenterEvent("phoneFinish"));
        }

        /**
         * 移动运营商下一步操作
         */
        @JavascriptInterface
        public void closeThisPage() {
            EventBus.getDefault().post(new AuthenticationCenterEvent("msg"));
        }

        /**
         * 调用改方法去发送短信
         *
         * @param phoneNumber 手机号码
         * @param message     短信内容
         **/
        @JavascriptInterface
        public void sendMessage(String phoneNumber, String message) {
            // 注册广播 发送消息
            //发送短信并且到发送短信页面
            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber));
            intent.putExtra("sms_body", message);
            startActivity(intent);
        }
    }

    /**
     * 重新拼接url
     */
    public static String getUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return "";
        }
        String ret_url = "";
        if (url.contains("?")) {
            ret_url = url + "&";
        } else {
            ret_url = url + "?";
        }
        ret_url += "clientType=android&appVersion="
                + ViewUtil.getAppVersion(App.getContext()) + "&deviceId="
                + ViewUtil.getDeviceId(App.getContext()) + "&mobilePhone=" +
                (App.getConfig().getLoginStatus() ? SpUtil.getString(Constant.CACHE_TAG_USERNAME) : "")
                + "&deviceName=" + ViewUtil.getDeviceName() + "&osVersion="
                + ViewUtil.getOsVersion() + "&appMarket="
                + App.getConfig().getChannelName() + "&appName=jsxjx";
        return ret_url.replace(" ", "");
    }

    class MyWebViewClient extends WebViewClient {

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();  // 接受所有网站的证书  解决https拦截问题
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mLoadingLayout.setStatus(LoadingLayout.Loading);
        }

        @Override
        public void onPageFinished(final WebView view, String url) {
            super.onPageFinished(view, url);
            mLoadingLayout.setStatus(LoadingLayout.Success);
            if (url.equals(mPhoneInfoUrl)) {
                mWebView.clearHistory();
            }
        }
    }

    class MyWebChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
        }

        @Override
        public void onReceivedTitle(final WebView view, String title) {
            super.onReceivedTitle(view, title);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
